import cv2
from imutils.video import VideoStream
import imutils
import numpy as np
import f_detector
import time
from playsound import playsound


detector = f_detector.eye_blink_detector()
COUNTER = 0
TOTAL = 0
min_avg_blink = 12
sec = 0
fps = 100
vs = VideoStream(src=1, fps=fps).start()
blink_data = np.array([0])
print(f"FPS is {fps}")
last_notif = 0

# create a window to display notification
background = np.zeros((100, 500, 3), dtype=np.uint8)
cv2.putText(background, "You haven't been blinking much!", (10, 30),
            cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)

current_time = time.time()
for _ in range(600*fps):

    im = vs.read()
    if im is None:
        pass
    im = cv2.flip(im, 1)
    im = imutils.resize(im, width=720)
    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    rectangles = detector.detector_faces(gray, 0)
    boxes_face = f_detector.convert_rectangles2array(rectangles, im)
    if len(boxes_face) != 0:
        areas = f_detector.get_areas(boxes_face)
        index = np.argmax(areas)
        rectangles = rectangles[index]
        COUNTER, TOTAL, leftEye, rightEye = detector.eye_blink(
            gray, rectangles, COUNTER, TOTAL)
        blink_data[-1] += TOTAL-np.sum(blink_data)

    if (sec % 60 < 1) and (last_notif > 50):
        if blink_data[-1] < min_avg_blink:
            playsound('ping.mov')
            cv2.imshow('blink_detection', background)
            cv2.waitKey(1000)
            cv2.destroyAllWindows()
        print(blink_data)
        last_notif = 0
        blink_data = np.append(blink_data, 0)
        print("Time taken: ", time.time() - current_time)
        current_time = time.time()
    sec += 1/fps
    last_notif += 1/fps

np.save('blink_data.npy', blink_data)
vs.stop()
print(f"Time taken: {time.time() - current_time}")
